package com.service;

import com.config.ExceptionConfig;
import com.dao.ItemsDao;
import com.dao.OrdersDao;
import com.entity.Carts;
import com.entity.Items;
import com.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author james-CAO
 * @title: OrderService
 * @projectName csm_emall_ssm
 * @description: orderService
 * @date 2020/10/12 11:41
 */
@Service
public class OrderService {

    @Autowired
    private CartService cartService;
    @Autowired
    private GoodService goodService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private ItemsDao itemsDao;

    /**
     * 保存订单
     */

    public int save(int userId) throws ExceptionConfig.MyException {
        List<Carts> cartsList = cartService.getList(userId);
        if (Objects.isNull(cartsList) || cartsList.isEmpty()){
            throw new ExceptionConfig.MyException("购物车没有商品");
        }
        /**
         * 验证库存
         */
        for (Carts cart : cartsList){
            /**验证购物车*/
            if (cart.getGood().getStock() < cart.getAmount()){
                throw new ExceptionConfig.MyException("商品 ["+ cart.getGood().getName()+"] 库存不足");
            }
            goodService.updateStock(cart.getGood().getId(), cart.getAmount());  //减库存
            goodService.updateSales(cart.getGood().getId(), cart.getAmount());  //加销量

        }
            int total = 0;//订单总数
            for (Carts cart : cartsList){
                total += cart.getGood().getPrice() * cart.getAmount();
            }
            Order order=new Order();
            order.setUserId(userId);
            order.setTotal(total);
            order.setAmount(cartsList.size());
            order.setStatus(Order.STAUS_UNPAY);
            order.setSystime(new Date());
            ordersDao.insert(order);
            int orderId=order.getId();
        for (Carts cart : cartsList) {
            Items item=new Items();
                item.setOrderId(orderId);
                item.setGoodId(cart.getGoodId());
                item.setPrice(cart.getGood().getPrice());
                item.setAmount(cart.getAmount());
                itemsDao.insert(item);
        }
        /**清空购物车*/
        cartService.clean(userId);
        return orderId;

    }
    public List<Order> getList(){
        return ordersDao.selectList();
    }



}
